<?php

class Util_Log {
	
	static public function veryHard($str = '',$hash = array()){
		$str.= Utils::h2s('; ',': ',$hash);
      	$log_file = APPLICATION_PATH . '/../log/log_'.date('Y-m-d');
      	if(!file_exists($log_file))fclose(fopen($log_file, 'w'));
      	$fh = fopen($log_file, 'a');
		fwrite($fh,date('c') . ' HARDLOG (X1) : ' . $str . "\n");
		fclose($fh);
	}
	
	static public function hard($hash){
		$writer = new Zend_Log_Writer_Stream(APPLICATION_PATH . '/../log/log_'.date('Y-m-d'));
      	$logger = new Zend_Log($writer);
      	$log_str = Utils::h2s('; ',': ',$hash);
      	
      	$trace = debug_backtrace();
      	$strace = substr($trace[0]['file'], strrpos($trace[0]['file'],'\\')) .'; ';
      	if(array_key_exists('line', $trace[0])){
      		$strace .= '(line: '.$trace[0]['line'].'); ';
      	}
      	$logger->log($log_str . ' TRACE :' . $strace, Zend_Log::DEBUG);
	}
	
	static public function fire($msg,$a1='fake',$a2='fake'){
		//throw new Exception(); // - żeby sprawdzić skad leci log.
		Zend_Registry::get('console')->log($msg, Zend_Log::DEBUG);
		
		if($a1!='fake'){
			Zend_Registry::get('console')->log($a1,Zend_Log::DEBUG);
		}
		if($a2!='fake'){
			Zend_Registry::get('console')->log($a2,Zend_Log::DEBUG);
		}
	}
	
	static public function fireSql($adapter){
		$profiler = new Zend_Db_Profiler_Firebug('SQL debug');
		$profiler->setEnabled(true);
		$adapter->setProfiler($profiler);
		return $adapter;
	}
	

	// odpowiednik :: print_r($var,true);
	static public function dump($var){
		ob_start();
		var_dump($var);
		$save = ob_get_contents();
		ob_end_clean();
		return $save;
	}
	
	// TODO ujednolicic - z ErrorHandler.php i ErrorController.php
	static public function handleError($errno,$errstr,$errfile,$errline,$errcontext){
		
		$context = array();
      	foreach($errcontext as $k => $v){
      		if(is_resource($v)){
      			array_push($context, array($k=>Utils::dump($v)));	
      		} else {
      			array_push($context, array($k=>$v));
      		}
      	}
		
      	Utils::logHard(array(
      		"error"=>$errstr,
      		"file"=>"$errfile (linia: $errline)",
      		"context"=>json_encode($context)
      	));
		
		die(json_encode(array(
			"success"=>false,"msg"=>$errstr,"stack"=>$context,
			"msgs"=>"$errfile <br/> (linia: $errline)."
		)));
		return true;
	}
}